package com.itzmn.java.javase.io.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Author: 张梦楠
 * @Date: 2018/12/25 17:13
 * 简书：https://www.jianshu.com/u/d611be10d1a6
 * 码云：https://gitee.com/zhangqiye
 * @Description: NIO模式下的文件读写
 */
public class FileNIO {

    public static void main(String[] args) {

        File file = new File("test.txt");
        FileInputStream inputStream = null;
        FileChannel channel = null;
        try {
            inputStream = new FileInputStream(file);
            channel = inputStream.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);

            System.out.println(buffer.capacity()+","+buffer.limit()+","+buffer.position());
            int read = channel.read(buffer);
            System.out.println("读取通道数据:"+buffer.capacity()+","+buffer.limit()+","+buffer.position());

            // 准备将buffer中的数据读出来
            buffer.flip();
            System.out.println("准备读取buffer数据:"+buffer.capacity()+","+buffer.limit()+","+buffer.position());


            System.out.println("读取buffer一部分数据:"+buffer.capacity()+","+buffer.limit()+","+buffer.position());
            System.out.println(new String(buffer.array()));
            buffer.clear();
            System.out.println("读取完一部分数据:"+buffer.capacity()+","+buffer.limit()+","+buffer.position());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                inputStream.close();
                channel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
